package com.api.util;

import com.aliyun.oss.*;
import com.aliyun.oss.model.*;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/*
    @ClassName AliyunOSSUtil
    @Description TODO
    @Date 2021/8/3、15:52
*/
@Component
public class AliyunOSSUtil {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);

    //这里endpoint 在你的bucket列表->点击你的bucket->点击概览中间就有，下面有截图
    private static String endpoint = "oss-cn-hangzhou.aliyuncs.com";

    //accessKeyId 、accessKeySecret 上面有说到哪里获取
    private static String accessKeyId = "LTAI5t6jzMnTow8aCbM1msGa";
    private static String accessKeySecret = "Cmz9tukwwfExaJp7U0HBpTH7tG0fic";
    //刚才新建的bucket名称
    private static String bucketName = "xiaodun";

    /**
     * 上传文件
     */
    public static String upLoad(File file) {
        logger.info("------OSS文件上传开始--------" + file.getName());

        //在刚才新建的bucket下面新建一个目录，这就是那个目录的名称
        String fileHost = "mall/images";

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());
        String fileUrl = "";

        // 判断文件
        if (file == null) {
            return null;
        }
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            // 判断容器是否存在,不存在就创建
            if (!client.doesBucketExist(bucketName)) {
                client.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                client.createBucket(createBucketRequest);
            }
            // 设置文件路径和名称
            fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
            System.out.println(fileUrl);
            //设置请求头
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentType("image/jpg");
            // 上传文件
            PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file, meta));
            //设置返回的url有效期为10年
            Date expiration = new Date(new Date().getTime() + 10 * 365 * 24 * 60 * 60 * 1000);
            GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, fileUrl, HttpMethod.GET);
            req.setExpiration(expiration);
            // 设置权限(公开读)
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            if (result != null) {
                logger.info("------OSS文件上传成功------" + client.generatePresignedUrl(req).toString());
            }
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
        } catch (ClientException ce) {
            logger.error(ce.getErrorMessage());
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }
        return fileUrl;
    }

    public static void download(String filePath, HttpServletResponse response) {

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        OSSObject ossObject = ossClient.getObject(bucketName, filePath);

        BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());

        try {
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            //通知浏览器以附件形式下载
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filePath, "utf-8"));

            byte[] car = new byte[1024];
            int len = 0;
            while ((len = in.read(car)) != -1) {
                out.write(car, 0, len);
            }
            out.flush();
            out.close();
            in.close();
            ossClient.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭OSSClient。
        ossClient.shutdown();
    }
}
